package org.gruposp2p.dnie.service.search;

import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.hibernate.search.jpa.FullTextEntityManager;
import org.hibernate.search.jpa.FullTextQuery;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.search.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Repository("documentToSignSearcher")
public class DocumentToSignSearcher {

    private static Logger logger =
            LoggerFactory.getLogger(DocumentToSignSearcher.class);

    private EntityManager entityManager;

    @PersistenceContext
    public void setEntityManager(EntityManager entityManager) {
            this.entityManager = entityManager;
    }

    @Transactional(readOnly = true)
    public <T> List<T> findByFullText(Class<T> entityClass, 
            String[] entityFields, String textToFind, int firstResult, int maxResults) {
        FullTextEntityManager fullTextEntityManager =
        org.hibernate.search.jpa.Search.getFullTextEntityManager(entityManager);
        MultiFieldQueryParser parser =
                new MultiFieldQueryParser(entityFields, new StandardAnalyzer());
        Query luceneQuery;
        try {
            luceneQuery = parser.parse(textToFind);
        } catch (ParseException e) {
            logger.error("Cannot parse [" + textToFind + "] to a full text query", e);
            return new ArrayList<T>(0);
        }
        FullTextQuery query =
                fullTextEntityManager.createFullTextQuery(luceneQuery, entityClass);
        return query.setFirstResult(firstResult)
                .setMaxResults(maxResults).getResultList();
    }
    
}
